#include "net.h"

int main(int argc, const char *argv[])
{
	int listenfd,connfd;
	struct sockaddr_in servaddr,cliaddr;
	socklen_t peerlen;
	char buf[64];
	int real_read;

	//填充结构体servaddr信息
	bzero(&servaddr,sizeof(servaddr));
	servaddr.sin_family = AF_INET;
	inet_pton(AF_INET,SERV_IP_ADDR,(void *)&servaddr.sin_addr);
	servaddr.sin_port = htons(SERV_PORT);

	if( -1 == (listenfd = socket(AF_INET,SOCK_STREAM,0)) )
	{//1.建立监听套接字
		perror("socket failed");
		return -1;
	}	
	printf("socket create success....\n");

	if(-1 == bind(listenfd,(struct sockaddr *)&servaddr,sizeof(servaddr)) )
	{//2.绑定IP和端口信息
		perror("bind failed");
		return -1;
	}
	printf("bind success....\n");

	if( -1 == listen(listenfd,10) )
	{//3.设置端口监听
		perror("listen failed");
		return -1;
	}
	printf("listen success....\n");

	bzero(&cliaddr,sizeof(cliaddr));
	peerlen = sizeof(cliaddr);
	if( (connfd = accept(listenfd,(struct sockaddr *)&cliaddr,&peerlen)) < 0)
	{//4.等待客户端连接
		perror("accept");
		return -1;
	}
	while(1)
	{//5.进行通信（读写文件描述符connfd）
		bzero(buf,sizeof(buf));

		if( (real_read = read(connfd,buf,sizeof(buf))) < 0)
		{
			perror("recv");
			return -1;
		}
		
		if( 0 == real_read)
		{
			break;
		}

		printf("Received: %s\n",buf);

		if( 0 == (strncasecmp(buf,QUIT_STR,strlen(QUIT_STR))) )
		{
			printf("client quit\n");
			break;
		}

		bzero(buf,sizeof(buf));

		printf(">");

		fgets(buf,32,stdin);

		write(connfd,buf,strlen(buf)-1);

		if( 0 == (strncasecmp(buf,QUIT_STR,strlen(QUIT_STR))) )
		{
			printf("client quit\n");
			break;
		}



	}
	//6.关闭套接字
	close(connfd);
	close(listenfd);
	return 0;
}
